package com.jsgt.greekfire.dialog;

import android.app.Dialog;
import android.content.Context;
import android.os.Bundle;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;

import com.jsgt.greekfire.R;

public class BottomMenuDialog<T> extends Dialog {
    private T[] values;
    private LinearLayout llItems;
    private OnItemClickListener<T> mListener;

    public BottomMenuDialog(@NonNull Context context) {
        super(context, R.style.DialogTheme);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.dialog_bottom_menu);

        Window window = getWindow();
        //设置弹出位置
        window.setGravity(Gravity.BOTTOM);
        //设置弹出动画
        window.setWindowAnimations(R.style.main_menu_animStyle);
        //设置对话框大小
        window.setLayout(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);

        findViewById(R.id.tv_cancel).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dismiss();
            }
        });
        llItems = findViewById(R.id.ll_items);
        refreshItems();
    }

    private void refreshItems() {
        if (llItems == null || values == null || values.length == 0) {
            return;
        }
        llItems.removeAllViews();
        for (T t : values) {
            View view = LayoutInflater.from(getContext()).inflate(R.layout.item_bottom_menu, llItems, false);
            TextView txv = view.findViewById(R.id.txv);
            txv.setText(t.toString());
            view.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    dismiss();
                    if (mListener != null) {
                        mListener.onItemClick(t);
                    }
                }
            });
            llItems.addView(view);
        }
    }

    public void setValues(T[] values) {
        this.values = values;
        refreshItems();
    }

    public void setOnItemClickListener(OnItemClickListener<T> mListener) {
        this.mListener = mListener;
    }

    public interface OnItemClickListener<T> {
        void onItemClick(T t);
    }
}
